/**   
 * Copyright © 2019 eSunny Info. Tech Ltd. All rights reserved.
 * 
 * @Description:TODO(功能)
 * @className AdminServiceImpl.java
 * @Package: com.erp.service 
 * @author: yj   
 * @date: 2019年1月16日 下午3:56:53 
 */
package com.erp.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.erp.dao.AdminDao;
import com.erp.dao.AdminDaoImpl;
import com.erp.dao.BaseDao;
import com.erp.po.Admin;
import com.erp.po.Categorys;
import com.erp.po.Products;
import com.erp.po.Providers;
import com.erp.util.DBHelper;
import com.erp.util.Page;

/**
 * @className AdminServiceImpl.java
 * @author yj
 * @Description:TODO( 管理员 业务逻辑层的实现 )
 * @Date 2019年1月16日
 */
public class AdminServiceImpl implements AdminService {

	private AdminDaoImpl ad;
	
	public AdminServiceImpl() {
		ad = new AdminDaoImpl();
	}
	
	/* (管理员 登录)
	 * 
	 */
	@Override
	public Admin findAdminByLogin(Admin admin) {

		try {
			Connection conn = DBHelper.getConnection();
			ResultSet set = ad.selectAdminByLogin(conn, admin);
			if (set.next()) {
				int adminId = set.getInt("admin_id");
				String adminName = set.getString("admin_name");
				String adminPassword = set.getString("admin_password");
				String date = set.getString("date_");
				String tel = set.getString("tel");
				
				return new Admin(adminId, adminName, adminPassword, date, tel);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ad.close();
			//System.out.println("关闭 连接池");
		}
		return null;
	}

	/* (管理员 注册)
	 * 
	 */
	@Override
	public int addAdmin(Admin admin) {
		Connection conn = null;
		//boolean f = false;
		int code = 0; // 300: 有空串     |  301: 重复值       | 302: 成功

		if (admin == null || admin.getAdminName().equals("") || admin.getAdminName().equals(" ")
				|| admin.getAdminPassword().equals("") || admin.getAdminPassword().equals(" ")
				|| admin.getTel().equals("") || admin.getTel().equals(" ")) {
			code = 300;
			return code;
		}
		
		try {
			conn = DBHelper.getConnection();
			
			// 1.查询数据库是否以有 该用户名 ( 如果有 return false 注册失败 ,,反之, 注册成功 )
			ResultSet set = ad.selectAdminByAdd(conn, admin);
			if (set.next()) {
				// return false 注册失败
				code = 301;
				return code;
			} else {
				// 可以注册
				// 进行事务处理
				conn.setAutoCommit(false);
				int i = ad.insertAdmin(conn, admin);
				conn.commit();
				conn.setAutoCommit(true);
				if (i > 0) {
					//f = true;
					code = 302;
					return code;
				} else {
					//f = false;
					code = 301;
					return code;
				}
			}
		} catch (SQLException e) {
			try {
				conn.rollback();
				conn.setAutoCommit(true);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			ad.close();
		}
		return code;
	}

	
	

	
}
